#coding: utf-8
import screen
import md5
import random
import object
import pygame
import tile
import keyboard
import map
from pygame.locals import *
from keys import *

class Game:
	instance = None

	def __init__(self, filename=None):
		"Инициализация приложения"
		pygame.init()
		self.actors = {}
		self.actors_by_map = {}
		self.objects = {}
		self.keyboard = keyboard.kController(self)
		self.screen = screen.Screen(self)
		self.currentMap = map.mController(self, "test_map")
		self.currentMap.boundaries = (12,12)
		self.mode = "map"
		Game.instance = self
	
	def mainLoop(self):
		"Основной цикл программы, обработка событий, ДОБАВИТЬ: обработка времени здесь же"
		self.Running = True
		self.screen.redrawMap()
		while self.Running:
			for event in pygame.event.get():
				if event.type == QUIT:
					sys.exit(0)
				if not hasattr(event, 'key'): continue
				if hasattr(event, 'key'): 
					self.keyboard.eval(event)
				if self.mode == "menu":
					self.screen.MenuShow()
					self.screen.redrawMap()
				if self.mode == "map":
					"Обработка событий во времени (NPC, прочее) здесь"
					self.screen.redrawMap()
	
	def registerActor(self, actor, asPlayer=False, map="no_map"):
		"Добавить актера в игру"
		rid = randomId()
		if rid in self.actors.keys():
			self.registerActor(actor, asPlayer, map)
		else:
			self.actors[rid] = actor
			if asPlayer:
				self.player = rid
			self.actors[rid].id = rid
			if map in self.actors_by_map.keys():
				self.actors_by_map[map].append(rid)
				self.currentMap.addActor(rid)
			else:
				self.actors_by_map[map] = [rid]
				self.currentMap.addActor(rid)
	
	def registerMap(self, map):
		pass

	def moveActor(self, actor, heading, map=None):
		"Передвинуть актера"
		if not map:
			map = self.currentMap.name
		if self.currentMap.passable((self.actors[actor].position()[0] + heading[0], self.actors[actor].position()[1] + heading[1])):
			self.currentMap.map[self.actors[actor].position()].pop(self.currentMap.map[self.actors[actor].position()].index(actor))
			self.actors[actor].move(heading)
			self.currentMap.addActor(actor)
			self.screen.ShowMessage('')
		else:
			self.screen.ShowMessage("Ouch! You ran into the wall") #get short descr from map here
			return False


	def jumpActor(self, actor, dest, map=None):
		"Телепортировать актера"
		if not map:
			map = self.currentMap.name
		self.actors[actor].jump(dest)


	def findActorByName(self, name, uniq=False):
		"Найти актера по имени"
		if not uniq:
			retList = [] 
		for i in self.actors.keys():
			if self.actors[i].name == name:
				if not uniq:
					retList.append(i) 
				else:
					return i
		if (not uniq):
			return retList

	def exit(self):
		"Выйти из игры, перейти к действиям после игры"
		self.Running = False
	
	def saveToFile(self, filename="save.g"):
		pass

def randomId():
	return md5.md5(str(random.random())).hexdigest()[:10]
